<template>
    <a-card title="标记工具" style="width: 300px;pointer-events: all;">
        <div class="controls">
            <a-button :type="isMarkerMode ? 'primary' : 'default'" @click="toggleMarkerMode" :disabled="!viewer">
                {{ isMarkerMode ? '退出标记模式' : '开始标记' }}
            </a-button>
            <a-button v-if="markers.length" type="link" @click="clearMarkers">清除所有标记</a-button>
        </div>

        <a-alert v-if="!viewer" message="Cesium viewer 未初始化，请确保已加载3D场景" type="warning" show-icon />

        <a-list :data-source="markers" size="small" class="marker-list">
            <template #renderItem="{ item }">
                <a-list-item>
                    <div class="marker-item">
                        <span>{{ item.name }}</span>
                        <div>
                            <a-button type="link" size="small" @click="editMarker(item)">编辑</a-button>
                            <a-button type="link" size="small" danger @click="onDeleteMarker(item)">删除</a-button>
                        </div>
                    </div>
                </a-list-item>
            </template>
        </a-list>

        <a-modal v-model:open="editModalVisible" title="编辑标记" @ok="handleEditOk" @cancel="editModalVisible = false">
            <a-form :model="editingMarker" layout="vertical">
                <a-form-item label="名称">
                    <a-input v-model:value="editingMarker.name" placeholder="请输入标记名称" />
                </a-form-item>
            </a-form>
        </a-modal>
    </a-card>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import * as Cesium from 'cesium';
import { useMapData } from '@/store';
import { getMarkers, addMarker, updateMarker, deleteMarker } from '@/api/api';
import { cartesian3ToDegreesHeight } from '@/cesiumTools/utils';

// 组件状态变量
const isMarkerMode = ref(false);        // 标记模式开关
const markers = ref([]);                // 存储所有标记点
const editModalVisible = ref(false);    // 编辑弹窗显示状态
const editingMarker = ref({ id: null, name: '' });  // 当前编辑的标记点
const viewer = ref(null);               // Cesium 3D场景实例
const mapStore = useMapData();          // 地图数据存储

// 创建标记点实体(3D模型)
const createMarkerEntity = (position, name) => ({
    // 将经纬度转换为3D坐标
    position: Cesium.Cartesian3.fromDegrees(position.longitude, position.latitude, position.height || 0),
    // 设置标记点图标
    billboard: {
        image: '/marker.svg',
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,  // 图标底部对齐
        scale: 0.8,
        heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,  // 相对于地面高度
        color: Cesium.Color.RED
    },
    // 设置标记点标签
    label: {
        text: name,
        font: '14px sans-serif',
        fillColor: Cesium.Color.WHITE,
        outlineColor: Cesium.Color.BLACK,
        outlineWidth: 2,
        style: Cesium.LabelStyle.FILL_AND_OUTLINE,  // 文字样式
        verticalOrigin: Cesium.VerticalOrigin.TOP,  // 标签顶部对齐
        pixelOffset: new Cesium.Cartesian2(0, -10)  // 标签位置偏移
    }
});

// 加载标记点
const loadMarkers = async () => {
    if (!viewer.value) return;
    const res = await getMarkers();
    if (res.code === 200 && Array.isArray(res.data)) {
        // 清除现有标记点
        markers.value.forEach(m => viewer.value.entities.remove(m.entity));
        // 创建新的标记点
        markers.value = res.data.map(markerData => {
            // 转为对象,因为后端可能把位置信息存为字符串,前端需要对象格式才能使用
            const position = typeof markerData.position === 'string' ? JSON.parse(markerData.position) : markerData.position;
            // 创建3D实体
            const entity = viewer.value.entities.add(createMarkerEntity(position, markerData.name));
            return { ...markerData, position, entity };
        });
    }
};

// 标记模式切换
const toggleMarkerMode = () => {
    isMarkerMode.value = !isMarkerMode.value;
    //获取地图事件处理器
    const handler = viewer.value.screenSpaceEventHandler;
    if (isMarkerMode.value) {
        //添加点击事件监听,movement 包含鼠标点击的位置信息
        handler.setInputAction((movement) => {
            // 把屏幕坐标转为笛卡尔坐标
            const cartesian = viewer.value.scene.pickPosition(movement.position);
            if (cartesian) {
                // 将3D坐标转换为经纬度和高度
                const [longitude, latitude, height] = cartesian3ToDegreesHeight(cartesian);
                // 添加新标记点(高度+5使标记点更明显)
                addNewMarker({
                    longitude,
                    latitude,
                    height: height + 5
                });
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    } else {
        // 退出标记模式: 移除点击事件监听
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }
};

// 添加新标记点
const addNewMarker = async (position) => {
    // 准备标记点数据
    const markerData = {
        name: `标记点 ${markers.value.length + 1}`,  // 默认名称
        position: {
            longitude: Number(position.longitude),
            latitude: Number(position.latitude),
            height: Number(position.height || 0)
        },
        type: 'default',
        building_id: null
    };
    // 调用后端接口添加标记点
    const res = await addMarker(markerData);
    if (res.code === 200 && res.data) {
        // 创建3D实体
        const entity = viewer.value.entities.add(createMarkerEntity(position, res.data.name));
        // 添加到标记点列表
        markers.value.push({ ...res.data, entity });
        // 打开编辑弹窗
        editingMarker.value = { id: res.data.id, name: res.data.name };
        editModalVisible.value = true;
    }
};

// 编辑标记点
const editMarker = () => {
    // 打开编辑弹窗并设置当前编辑的标记点
    editModalVisible.value = true;
};

// 保存编辑
const handleEditOk = async () => {
    // 调用后端API更新标记点
    const res = await updateMarker(editingMarker.value.id, { name: editingMarker.value.name });
    if (res?.code === 200 && res.data) {
        //// 在标记点数组中找到要更新的那个标记点
        const marker = markers.value.find(m => m.id === editingMarker.value.id);
        if (marker) {
            marker.name = res.data.name;
            marker.entity.label.text = res.data.name;
        }
        message.success('更新标记点成功');
    }
    editModalVisible.value = false;
};

// 删除标记点
const onDeleteMarker = async (marker) => {
    // 调用后端API删除标记点
    const res = await deleteMarker(marker.id);
    if (res.code === 200) {
        // 移除3D实体
        viewer.value.entities.remove(marker.entity);
        // 从列表中移除
        markers.value = markers.value.filter(m => m.id !== marker.id);
        message.success('删除标记点成功');
    }
};

// 清除所有标记点
const clearMarkers = async () => {
    // 逐个删除所有标记点
    for (const marker of markers.value) {
        await onDeleteMarker(marker);
    }
    markers.value = [];
    message.success('已清除所有标记点');
};


// 组件挂载时初始化
onMounted(() => {
    viewer.value = mapStore.Viewer;
    if (viewer.value) loadMarkers();
});
</script>

<style scoped>
.controls {
    margin-bottom: 12px;
    display: flex;
    gap: 8px;
}

.marker-list {
    max-height: 500px;
    overflow-y: auto;
}

.marker-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    border-bottom: 1px solid #f0f0f0;
}

.marker-item:last-child {
    border-bottom: none;
}

.marker-list::-webkit-scrollbar {
    width: 4px;
}

.marker-list::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

.marker-list::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 2px;
}

.marker-list::-webkit-scrollbar-thumb:hover {
    background: #555;
}
</style>